import 'dart:convert';
import 'package:flutter/services.dart' show rootBundle;
import 'package:shared_preferences/shared_preferences.dart';

class VideoSite {
  final String id;
  final String name;
  final String api;
  final String detail;
  final bool isAdult;

  const VideoSite({
    required this.id,
    required this.name,
    required this.api,
    required this.detail,
    required this.isAdult,
  });
}

/// 运行时站点列表（从 assets 或导入的 JSON 加载）
List<VideoSite> kVideoSites = [];

class SitesRepository {
  static const String prefsKey = 'custom_sites_json';
  static const String prefsTimeKey = 'custom_sites_time';

  /// 从 JSON 字符串解析站点列表
  static List<VideoSite> parseSitesJson(String jsonStr) {
    final map = jsonDecode(jsonStr) as Map<String, dynamic>;
    final apiSite = map['api_site'] as Map<String, dynamic>? ?? {};
    final List<VideoSite> list = [];
    apiSite.forEach((key, value) {
      final v = value as Map<String, dynamic>;
      String clean(String s) => s.replaceAll('`', '').trim();
      list.add(VideoSite(
        id: key,
        name: (v['name'] ?? key).toString(),
        api: clean((v['api'] ?? '').toString()),
        detail: clean((v['detail'] ?? '').toString()),
        isAdult: (v['is_adult'] ?? false) == true,
      ));
    });
    return list;
  }

  /// 加载站点，合并内置站点和自定义站点
  static Future<List<VideoSite>> loadSites() async {
    final prefs = await SharedPreferences.getInstance();
    final now = DateTime.now().millisecondsSinceEpoch ~/ 1000;
    final custom = prefs.getString(prefsKey);
    final customTime = prefs.getInt(prefsTimeKey) ?? 0;
    
    try {
      // 加载内置站点
      final assetStr = await rootBundle.loadString('assets/sites.json');
      final assetMap = jsonDecode(assetStr) as Map<String, dynamic>;
      final List<VideoSite> builtInSites = parseSitesJson(assetStr);
      
      // 如果有自定义配置且在缓存时间内，加载自定义站点
      if (custom != null && custom.isNotEmpty) {
        final customSites = parseSitesJson(custom);
        
        // 合并站点列表（自定义站点优先，覆盖同ID的内置站点）
        final Map<String, VideoSite> mergedSites = {};
        
        // 先添加内置站点
        for (final site in builtInSites) {
          mergedSites[site.id] = site;
        }
        
        // 然后添加自定义站点（会覆盖同ID的内置站点）
        for (final site in customSites) {
          mergedSites[site.id] = site;
        }
        
        kVideoSites = mergedSites.values.toList();
        return kVideoSites;
      }
      
      // 没有自定义配置，只返回内置站点
      kVideoSites = builtInSites;
      return kVideoSites;
      
    } catch (e) {
      print('站点加载失败: $e');
      // 兜底：如果解析失败，保留内置少量站点
      kVideoSites = [
        VideoSite(
          id: '360zy',
          name: 'TV-360资源',
          api: 'https://360zy.com/api.php/provide/vod',
          detail: 'https://360zy.com',
          isAdult: false,
        ),
      ];
      print('使用兜底站点配置，共 ${kVideoSites.length} 个站点');
      return kVideoSites;
    }
  }

  /// 导入站点 JSON（客户端导入），并缓存到本地
  static Future<void> importSitesJson(String jsonStr) async {
    final prefs = await SharedPreferences.getInstance();
    
    // 获取现有的自定义配置（如果有）
    final existingCustomJson = prefs.getString(prefsKey);
    Map<String, dynamic> mergedData = {};
    
    if (existingCustomJson != null && existingCustomJson.isNotEmpty) {
      try {
        final existingData = jsonDecode(existingCustomJson) as Map<String, dynamic>;
        mergedData = Map.from(existingData);
      } catch (e) {
        print('解析现有自定义配置失败: $e');
      }
    }
    
    // 解析新导入的JSON
    try {
      final newData = jsonDecode(jsonStr) as Map<String, dynamic>;
      final newSites = newData['api_site'] as Map<String, dynamic>? ?? {};
      
      // 合并站点配置
      if (mergedData['api_site'] == null) {
        mergedData['api_site'] = <String, dynamic>{};
      }
      
      final mergedSites = Map<String, dynamic>.from(mergedData['api_site'] as Map<String, dynamic>);
      mergedSites.addAll(newSites);
      mergedData['api_site'] = mergedSites;
      
      // 保存合并后的配置
      final mergedJson = jsonEncode(mergedData);
      await prefs.setString(prefsKey, mergedJson);
      final now = DateTime.now().millisecondsSinceEpoch ~/ 1000;
      await prefs.setInt(prefsTimeKey, now);
      kVideoSites = parseSitesJson(mergedJson);
    } catch (e) {
      print('解析导入的JSON失败: $e');
      rethrow;
    }
  }

  /// 获取当前使用的自定义JSON（如果有）
  static Future<String?> getCustomSitesJson() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(prefsKey);
  }

  /// 检查是否正在使用自定义站点配置
  static Future<bool> isUsingCustomSites() async {
    final prefs = await SharedPreferences.getInstance();
    final custom = prefs.getString(prefsKey);
    return custom != null && custom.isNotEmpty;
  }

  /// 重置为默认站点配置
  static Future<void> resetToDefaultSites() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(prefsKey);
    await prefs.remove(prefsTimeKey);
    await loadSites(); // 重新加载默认配置
  }

  /// 删除所有自定义站点（清空自定义配置）
  static Future<void> deleteAllSites() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(prefsKey);
    await prefs.remove(prefsTimeKey);
    kVideoSites = []; // 清空当前站点列表
  }

  /// 检查站点是否为内置站点
  static Future<bool> isBuiltInSite(VideoSite site) async {
    final prefs = await SharedPreferences.getInstance();
    final customJson = prefs.getString(prefsKey);
    
    // 如果没有自定义配置，所有站点都是内置的
    if (customJson == null || customJson.isEmpty) {
      return true;
    }
    
    // 解析自定义配置，检查站点是否在其中
    try {
      final customData = jsonDecode(customJson) as Map<String, dynamic>;
      final customSites = customData['api_site'] as Map<String, dynamic>? ?? {};
      
      // 如果站点ID在自定义配置中，说明是自定义站点
      if (customSites.containsKey(site.id)) {
        return false;
      }
      
      // 否则检查是否在assets/sites.json中
      try {
        final assetStr = await rootBundle.loadString('assets/sites.json');
        final assetData = jsonDecode(assetStr) as Map<String, dynamic>;
        final assetSites = assetData['api_site'] as Map<String, dynamic>? ?? {};
        return assetSites.containsKey(site.id);
      } catch (e) {
        print('检查内置站点失败（assets）: $e');
        return true; // 出错时默认认为是内置站点
      }
    } catch (e) {
      print('检查内置站点失败（custom）: $e');
      return true; // 出错时默认认为是内置站点
    }
  }

  /// 分离内置站点和自定义站点
  static Future<Map<String, List<VideoSite>>> separateSites(List<VideoSite> allSites) async {
    final List<VideoSite> builtInSites = [];
    final List<VideoSite> customSites = [];
    
    for (final site in allSites) {
      final isBuiltIn = await isBuiltInSite(site);
      if (isBuiltIn) {
        builtInSites.add(site);
      } else {
        customSites.add(site);
      }
    }
    
    return {
      'builtIn': builtInSites,
      'custom': customSites,
    };
  }
}